﻿/// <summary>
/// data   :2016-04-27
/// author :fanzhengyong
/// lua组件，可以理解为lua script容器，持有者。从MonoBehaviour继承，调用lua中对应
/// MonoBehaviour的函数。调用lua的对象通过添加本组件，设置lua的路径和模块名称（可选）
/// 调用lua script。每次调用都把gameObject和transform传递过了lua。
/// 举例说明对应：如果lua中存在Awake函数，那么LuaHolder:Awake()调用的是lua中的Awake。
/// 需要注意的是lua script必须写成module
/// </summary>

using UnityEngine;
using System.Collections;

namespace UEngine
{
    [AddComponentMenu("Custom/Lua/LuaCom")]
    public class LuaCom : MonoBehaviour
    {
        public  string       luaScriptPath;
        public  string       luaScriptModuleName;

        private LuaScriptMgr m_luaScriptMgr           = null;
        private bool         m_isInit                 = false;
        private string       m_goInLuaState;
        private string       m_trsInLuaState;

        void Awake()
        {
            if (
                (!StringHelper.IsValidString(luaScriptPath)) ||
                (!StringHelper.IsValidString(luaScriptModuleName))
            )
            {
                return;
            }
            m_goInLuaState   = luaScriptModuleName + ".gameObject";
            m_trsInLuaState  = luaScriptModuleName + ".transform";
            
            m_luaScriptMgr   = ULuaManager.Instance().GetLuaScriptMgr();
            if (m_luaScriptMgr == null)
            {
                return;
            }

            m_luaScriptMgr.DoFile(luaScriptPath);
        
            m_isInit = true;

            CallLuaFunction("Awake");
        }

        void Start()
        {
            CallLuaFunction("Start");
        }

        void Update()
        {
            CallLuaFunction("Update");
        }

        void OnDestroy()
        {
            CallLuaFunction("OnDestroy");
            Util.ClearMemory();
            m_isInit = false;
        }

        /// <summary>
        /// 调用Lua中对应的函数。
        /// </summary>
        /// <param name="name">函数名称</param>
        /// <param name="args"></param>
        private void CallLuaFunction(string name, params object[] args)
        {
            if (!m_isInit)
            {
                return;
            }

            m_luaScriptMgr.lua[m_goInLuaState]   = gameObject;
            m_luaScriptMgr.lua[m_trsInLuaState]  = transform;
            m_luaScriptMgr.CallLuaFunction(luaScriptModuleName + "." + name, args);
        }
    }
}

